<template>
  <div class="login-container">
    <el-form ref="loginForm" :model="loginForm" :rules="loginRules" class="login-form" autocomplete="on" label-position="left">
      <div class="title-container">
        <h3 class="title">登录表单</h3>
        <el-tabs v-model="activeLoginType" @tab-click="changeLoginType">
          <el-tab-pane label="用户名密码登录" name="usernamePassword" />
          <el-tab-pane label="手机验证码登录" name="mobilePhoneCode" />
        </el-tabs>
      </div>
      <div v-if="activeLoginType==1" class="username-login">
        <el-form-item prop="username">
          <span class="svg-container">
            <svg-icon icon-class="user" />
          </span>
          <el-input
            ref="username"
            v-model="loginForm.username"
            placeholder="Username"
            name="username"
            type="text"
            tabindex="1"
            autocomplete="on"
          />
        </el-form-item>
        <el-tooltip v-model="capsTooltip" content="Caps lock is On" placement="right" manual>
          <el-form-item prop="password">
            <span class="svg-container">
              <svg-icon icon-class="password" />
            </span>
            <el-input
              :key="passwordType"
              ref="password"
              v-model="loginForm.password"
              :type="passwordType"
              placeholder="Password"
              name="password"
              tabindex="2"
              autocomplete="on"
              @keyup.native="checkCapslock"
              @blur="capsTooltip = false"
              @keyup.enter.native="handleLogin"
            />
            <span class="show-pwd" @click="showPwd">
              <svg-icon :icon-class="passwordType === 'password' ? 'eye' : 'eye-open'" />
            </span>
          </el-form-item>
        </el-tooltip>
      </div>
      <div v-else class="phoneCodeLogin">
        <div class="one-line">
          <el-form-item prop="phoneNo">
            <el-select v-model="activeAreaCode" filterable placeholder="选择国家/地区" @change="changeArea">
              <el-option
                v-for="item in areaCodes"
                :key="item.label"
                :label="item.label"
                :value="item.value"
              >
                <span style="float: left">{{ item.label }}</span>
                <span style="float: right; color: #8492a6; font-size: 13px">{{ item.value }}</span>
              </el-option>
            </el-select>
            <el-input
              ref="phoneNo"
              v-model="loginForm.phoneNo"
              name="phoneNo"
              class="phone-no"
              tabindex="3"
              autocomplete="on"
              placeholder="请输入手机号码"
            />
            <el-button type="info" :disabled="disabled" @click="sendPhoneCode">{{ sendCodeText }}</el-button>
          </el-form-item>
        </div>
        <div class="one-line">
          <el-form-item prop="phoneCode">
            <el-input
              ref="phoneCode"
              v-model="loginForm.phoneCode"
              name="phoneCode"
              class="phone-code"
              tabindex="4"
              placeholder="请输入验证码"
              @keyup.enter.native="handleLogin"
            />
          </el-form-item>
        </div>
      </div>
      <el-button
        :loading="loading"
        type="primary"
        style="width:100%;margin-bottom:30px;"
        @click.native.prevent="handleLogin"
      >
        登录
      </el-button>
      <div>
        <router-link to="/resetPass" class="forget-password">忘记密码</router-link>
        <router-link class="register" to="/register">注册账号</router-link>
        <!-- 
        <a class="forget-password" name="forgetPass" href="/#/" >忘记密码</a>
        <a class="register" name="registerAccount" @click="gotoRegPage">注册账号</a> 
        -->
      </div>
    </el-form>
  </div>
</template>

<script>
import { validUsername, isNumber } from '@/utils/validate'
// import SocialSign from './components/SocialSignin'
import { sendMessageCode } from '@/api/user'
import { Message } from 'element-ui'
export default {
  name: 'Login',
  // components: { SocialSign },
  data() {
    const validateUsername = (rule, value, callback) => {
      if (!validUsername(value)) {
        callback(new Error('Please enter the correct user name'))
      } else {
        callback()
      }
    }
    const validatePassword = (rule, value, callback) => {
      if (value.length < 6) {
        callback(new Error('The password can not be less than 6 digits'))
      } else {
        callback()
      }
    }
    const validatePhoneNo = (rule, value, callback) => {
      if (value.length !== 11 || !isNumber(value)) {
        callback(new Error('手机号码必须是11位数字'))
      } else {
        if (value.charAt(0) !== '1' || parseInt(value.charAt(1)) < 3) {
          callback(new Error('输入的手机号码不是有效的手机号'))
        } else {
          callback()
        }
      }
    }
    const validatePhoneCode = (rule, value, callback) => {
      if (!value) {
        callback(new Error('验证码不能为空'))
      } else {
        if (value.length !== 6 || !isNumber(value)) {
          callback(new Error('验证码必须是6位数字'))
        } else {
          callback()
        }
      }
    }
    return {
      // 1-用户名密码登录；2-手机号验证码登录
      activeLoginType: '1',
      activeAreaCode: '+86',
      sendCodeText: '发送验证码',
      disabled: false,
      areaCodes: [{ label: '+86', value: '中国大陆' },
        { label: '+1', value: '美国&加拿大' },
        { label: '+852', value: '中国香港' },
        { label: '+886', value: '中国台湾' },
        { label: '+81', value: '日本' }
      ],
      loginForm: {
        username: 'heshengfu',
        password: 'heshengfu123',
        phoneNo: '',
        phoneCode: ''
      },
      loginRules: {
        username: [{ required: true, trigger: 'blur', validator: validateUsername }],
        password: [{ required: true, trigger: 'blur', validator: validatePassword }],
        phoneNo: [{ required: true, trigger: 'blur', validator: validatePhoneNo }],
        phoneCode: [{ required: true, trigger: 'blur', validator: validatePhoneCode }]
      },
      passwordType: 'password',
      capsTooltip: false,
      loading: false,
      showDialog: false,
      redirect: undefined,
      otherQuery: {}
    }
  },
  watch: {
    $route: {
      handler: function(route) {
        const query = route.query
        if (query) {
          this.redirect = query.redirect
          this.otherQuery = this.getOtherQuery(query)
        }
      },
      immediate: true
    }
  },
  created() {
    // window.addEventListener('storage', this.afterQRScan)
  },
  mounted() {
    // if (this.activeLoginType === '1') {
    //   if (this.loginForm.username === '') {
    //     this.$refs.username.focus()
    //   } else if (this.loginForm.password === '') {
    //     this.$refs.password.focus()
    //   }
    // } else {
    //   if (this.loginForm.phoneNo === '') {
    //     this.$refs.phoneNo.focus()
    //   } else if (this.loginForm.phoneCode === '') {
    //     this.$refs.phoneCode.focus()
    //   }
    // }
  },
  destroyed() {
    // window.removeEventListener('storage', this.afterQRScan)
  },
  methods: {
    checkCapslock({ shiftKey, key } = {}) {
      if (key && key.length === 1) {
        if (shiftKey && (key >= 'a' && key <= 'z') || !shiftKey && (key >= 'A' && key <= 'Z')) {
          this.capsTooltip = true
        } else {
          this.capsTooltip = false
        }
      }
      if (key === 'CapsLock' && this.capsTooltip === true) {
        this.capsTooltip = false
      }
    },
    changeLoginType(val) {
      if (val.index === '0') {
        this.activeLoginType = '1'
      } else {
        this.activeLoginType = '2'
      }
    },
    changeArea(val) {
      console.log('val', val)
    },
    sendPhoneCode() {
      if (this.disabled) {
        return
      }
      const phoneNo = this.activeAreaCode.substr(1) + this.loginForm.phoneNo
      console.log('phoneNo', phoneNo)
      sendMessageCode(phoneNo).then(res => {
        if (res.data.status === 200) {
          Message({
            message: '发送验证码成功',
            type: 'success'
          })
        } else {
          Message.error('发送验证码失败')
        }
      })
      let time = 60
      const myInterval = setInterval(() => {
        if (time > 0) {
          time--
          this.sendCodeText = time + 's后重发'
          this.disabled = true
        } else {
          this.sendCodeText = '发送验证码'
          this.disabled = false
          clearInterval(myInterval)
        }
      }, 1000)
    },
    showPwd() {
      if (this.passwordType === 'password') {
        this.passwordType = ''
      } else {
        this.passwordType = 'password'
      }
      this.$nextTick(() => {
        this.$refs.password.focus()
      })
    },
    handleLogin() {
      this.$refs.loginForm.validate(valid => {
        if (valid) {
          this.loading = true
          if (this.activeLoginType === '1') {
            const username = this.loginForm.username
            const password = this.loginForm.password
            this.$store.dispatch('user/login', { username: username, password: password })
              .then(() => {
                this.$router.push({ path: this.redirect || '/', query: this.otherQuery })
                this.loading = false
              })
          } else {
            const phoneNo = this.loginForm.phoneNo
            const phoneCode = this.loginForm.phoneCode
            this.$store.dispatch('user/mobileLogin', { phoneNo: phoneNo, phoneCode: phoneCode })
              .then(() => {
                this.$router.push({ path: this.redirect || '/', query: this.otherQuery })
                this.loading = false
              })
          }
        }
      })
    },
    getOtherQuery(query) {
      return Object.keys(query).reduce((acc, cur) => {
        if (cur !== 'redirect') {
          acc[cur] = query[cur]
        }
        return acc
      }, {})
    },
    gotoRegPage(){
      console.log('跳转到注册页面')
      this.$store.dispatch('user/gotoRegisterPage').then(()=>{
        // location.reload()
        this.$router.push({path: '/register'})
      })
    },
    gotoResetPass(){
      console.log('跳转到重置密码界面')
    }
    // afterQRScan() {
    //   if (e.key === 'x-admin-oauth-code') {
    //     const code = getQueryObject(e.newValue)
    //     const codeMap = {
    //       wechat: 'code',
    //       tencent: 'code'
    //     }
    //     const type = codeMap[this.auth_type]
    //     const codeName = code[type]
    //     if (codeName) {
    //       this.$store.dispatch('LoginByThirdparty', codeName).then(() => {
    //         this.$router.push({ path: this.redirect || '/' })
    //       })
    //     } else {
    //       alert('第三方登录失败')
    //     }
    //   }
    // }
  }
}
</script>

<style lang="scss">
/* 修复input 背景不协调 和光标变色 */
/* Detail see https://github.com/PanJiaChen/vue-element-admin/pull/927 */

$bg:#2d3a4b;
$light_gray:#fff;
$cursor: #fff;

@supports (-webkit-mask: none) and (not (cater-color: $cursor)) {
  .login-container .el-input input {
    color: $cursor;
  }
}

/* reset element-ui css */
.login-container {
  .el-input {
    display: inline-block;
    height: 47px;
    width: 85%;
    input {
      background: transparent;
      border: 0px;
      -webkit-appearance: none;
      border-radius: 0px;
      padding: 12px 5px 12px 15px;
      color: $light_gray;
      height: 47px;
      caret-color: $cursor;

      &:-webkit-autofill {
        box-shadow: 0 0 0px 1000px $bg inset !important;
        -webkit-text-fill-color: $cursor !important;
      }
    }
  }

  .el-form-item {
    border: 1px solid rgba(255, 255, 255, 0.1);
    background: rgba(0, 0, 0, 0.1);
    border-radius: 5px;
    color: #454545;
  }
  .one-line .el-select.el-select--medium {
    width: 30%;
    float: left;
    .el-input.el-input--medium.el-input--suffix {
      width: 100%;
      border-style: solid;
      border-width: 2px;
      border-color: #FFF;
    }
  }
  .one-line .phone-no.el-input.el-input--medium {
    float: left;
    width: 40%;
    border-style: solid;
    border-width: 2px;
    border-color: #FFF;
    border-left-width: 0;
  }
  .one-line .phone-code.el-input.el-input--medium {
    width: 100%;
    border: solid 2px #fff;
    margin-top: 10px;
    margin-bottom: 10px;
  }
  .one-line .el-button.el-button--info.el-button--medium {
    height: 47px;
    margin-left: 10px;
    width: 27%;
  }

}
</style>

<style lang="scss" scoped>
$bg:#2d3a4b;
$dark_gray:#889aa4;
$light_gray:#eee;

#app {
  height: 100%;
  width: 100%;
  background-color: #2d3a4b;
}

.login-container {
  width: 50%;
  height: 600px;
  margin-left: 20%;
  margin-top: 150px;
  background-color: #00DDDD;
  overflow: hidden;
  .el-tabs__nav > .el-tabs__item {
    font-weight: 800;
    cursor: pointer;
  }

  .login-form {
    position: relative;
    width: 520px;
    max-width: 100%;
    padding: 160px 35px 0;
    margin: 0 auto;
    overflow: hidden;
  }

  .tips {
    font-size: 14px;
    color: #fff;
    margin-bottom: 10px;

    span {
      &:first-of-type {
        margin-right: 16px;
      }
    }
  }

  .svg-container {
    padding: 6px 5px 6px 15px;
    color: $dark_gray;
    vertical-align: middle;
    width: 30px;
    display: inline-block;
  }

  .title-container {
    position: relative;

    .title {
      font-size: 26px;
      color: $light_gray;
      margin: 0px auto 40px auto;
      text-align: center;
      font-weight: bold;
    }
  }

  .show-pwd {
    position: absolute;
    right: 10px;
    top: 7px;
    font-size: 16px;
    color: $dark_gray;
    cursor: pointer;
    user-select: none;
  }

  .thirdparty-button {
    position: absolute;
    right: 0;
    bottom: 6px;
  }

  .register, .forget-password{
    width: 20%;
    height: 35px;
    color: blue;
    margin-right: 20px;
    cursor: pointer;
  }

  @media only screen and (max-width: 470px) {
    .thirdparty-button {
      display: none;
    }
  }
}
</style>
